//
//  TopicDetailViewController.m
//  Zaker
//
//  Created by dllo on 16/3/11.
//  Copyright © 2016年 dllo. All rights reserved.
//

#import "TopicDetailViewController.h"

@interface TopicDetailViewController ()<UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, retain)UITableView *tableView;
@property (nonatomic, retain)NSDictionary *expert;//专家信息
@property (nonatomic, retain)NSMutableArray *hotArr;//热门提问数据
@property (nonatomic, retain)NSMutableArray *latesArr;//最新提问数据
@property (nonatomic, retain)NSMutableArray *questionArr;
@property (nonatomic, retain)NSMutableArray *answerArr;
@property (nonatomic, retain)UIButton *concerBtn;
@property (nonatomic, assign)NSInteger i;
@property (nonatomic, retain)UILabel *noRequset;
@property (nonatomic, retain)UIButton *spreadBtn;
@property (nonatomic, retain)UILabel *descripLable;
@property (nonatomic, retain)UILabel *nameLable;
@property (nonatomic, retain) BaseView *header;//上面的头部区域
@property (nonatomic, assign)BOOL isSpread;//是否展开
@property (nonatomic, retain)NSMutableArray *arr;//查询数据库中的数据
@property (nonatomic, retain) UIView *naviBar;
@property (nonatomic, retain) BaseView *bigView;
@property (nonatomic, retain) BaseView *smallView;
@property (nonatomic, retain) NSMutableArray *dataArr;
@property (nonatomic, retain) UILabel *titleLabel;

@property (nonatomic, strong) CoreDataManager *manager;

@end

@implementation TopicDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.manager = [CoreDataManager defaults];
    [self handleData];
    [self createTableView];
    [self createNaviBar];
}

- (void)createNaviBar
{
    self.naviBar = [[UIView alloc] initWithFrame:CGRectMake(0, 20, SCREEN_WIDTH, 50)];
    _naviBar.backgroundColor = [UIColor colorWithRed:0.890 green:0.161 blue:0.188 alpha:1.000];
    [self.view addSubview:_naviBar];
    _naviBar.alpha = 0;
    
    self.titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH - 150, 50)];
    _titleLabel.center = CGPointMake(self.view.center.x, _titleLabel.center.y);
    _titleLabel.textColor = [UIColor whiteColor];
    _titleLabel.text = _model.alias;
    [_naviBar addSubview:_titleLabel];
    //_titleLabel.alpha = 0;
    
    UIButton *leftButton = [UIButton buttonWithType:UIButtonTypeCustom];
    leftButton.frame = CGRectMake(20 * WIDTH, 0, 25 * WIDTH, 25 * WIDTH);
    leftButton.center = CGPointMake(leftButton.center.x, _naviBar.center.y);
    [leftButton setImage:[UIImage imageNamed:@"iconfont-jiantou"] forState:UIControlStateNormal];
    [leftButton addTarget:self action:@selector(buttonClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:leftButton];
}

- (void)buttonClick
{
    [self.navigationController popViewControllerAnimated:YES];
}

//数据处理
-(void)handleData
{
    NSString *path = [NSString stringWithFormat:@"http://c.m.163.com/newstopic/qa/%@.html", _model.expertId];
    [LHAFNetworkTool getUrl:path body:nil response:LHJSON requestHeadFile:nil success:^(NSURLSessionDataTask *task, id resposeObject) {
        //专家信息
        self.expert = resposeObject[@"data"][@"expert"];
        //最热提问
        self.hotArr = resposeObject[@"data"][@"hotList"];
        //最新提问
        self.latesArr = resposeObject[@"data"][@"latestList"];
        
        self.dataArr = [NSMutableArray array];
        self.dataArr = _latesArr;
        NSMutableArray *qArr = [NSMutableArray array];
        NSMutableArray *aArr = [NSMutableArray array];
        for (NSDictionary *dic in _dataArr) {
            NSDictionary *questionDic = dic[@"question"];
            NSDictionary *answerDic = dic[@"answer"];
            [qArr addObject:questionDic];
            [aArr addObject:answerDic];
        }
        self.questionArr = [TopicDetailModel modelHandlerWithArray:qArr];
        self.answerArr = [TopicDetailModel modelHandlerWithArray:aArr];
        
        //没有回复时提醒的lable
        if (_questionArr.count == 0){
            self.noRequset = [[UILabel alloc]initWithFrame:CGRectMake(self.view.frame.size.width / 5, _tableView.frame.size.height / 6 * 4, self.view.frame.size.width / 5 * 3, _tableView.frame.size.height / 4)];
        }
        [self createHeadView];
//        [self createNaviBar];
        [_tableView reloadData];
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        
    }];
}

- (void)dealData
{
    NSString *path = [NSString stringWithFormat:@"http://c.m.163.com/newstopic/qa/%@.html", _model.expertId];
    [LHAFNetworkTool getUrl:path body:nil response:LHJSON requestHeadFile:nil success:^(NSURLSessionDataTask *task, id resposeObject) {
        //专家信息
        self.expert = resposeObject[@"data"][@"expert"];
        //最热提问
        self.hotArr = resposeObject[@"data"][@"hotList"];
        //最新提问
        self.latesArr = resposeObject[@"data"][@"latestList"];
        
        //self.dataArr = [NSMutableArray array];
       // self.dataArr = _latesArr;
        NSMutableArray *qArr = [NSMutableArray array];
        NSMutableArray *aArr = [NSMutableArray array];
        for (NSDictionary *dic in _dataArr) {
            NSDictionary *questionDic = dic[@"question"];
            NSDictionary *answerDic = dic[@"answer"];
            [qArr addObject:questionDic];
            [aArr addObject:answerDic];
        }
        self.questionArr = [TopicDetailModel modelHandlerWithArray:qArr];
        self.answerArr = [TopicDetailModel modelHandlerWithArray:aArr];
        
        //没有回复时提醒的lable
        if (_questionArr.count == 0){
            self.noRequset = [[UILabel alloc]initWithFrame:CGRectMake(self.view.frame.size.width / 5, _tableView.frame.size.height / 6 * 4, self.view.frame.size.width / 5 * 3, _tableView.frame.size.height / 4)];
        }
//        [self createHeadView];
//        [self createNaviBar];
        [_tableView reloadData];
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        
    }];
}

- (void)createHeadView
{
    self.header = [[BaseView alloc] init];
    
    //背景图
    UIImageView *backImg = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 190)];
    [backImg sd_setImageWithURL:[NSURL URLWithString:_model.picurl] placeholderImage:[UIImage imageNamed:@"User_Profiles_bg"]];
    [_header addSubview:backImg];
    
    UIView *blackView = [[UIView alloc] initWithFrame:backImg.frame];
    blackView.backgroundColor = [UIColor blackColor];
    blackView.alpha = 0.3;
    [_header addSubview:blackView];
    
    //作者介绍
    UILabel *jieshaoLable = [[UILabel alloc]initWithFrame:CGRectMake(self.view.frame.size.width / 5, backImg.frame.size.height / 4, backImg.frame.size.width / 5 * 3, 60)];
    jieshaoLable.numberOfLines = 2;
    //jieshaoLable.font = [UIFont systemFontOfSize:16];
    jieshaoLable.text = _model.alias;
    jieshaoLable.textColor = [UIColor whiteColor];
    [_header addSubview:jieshaoLable];
    
    //关注数量
    UILabel *concernLable = [[UILabel alloc]initWithFrame:CGRectMake(0, jieshaoLable.frame.origin.y + jieshaoLable.frame.size.height + 10, 120, 20)];
    concernLable.center = CGPointMake(self.view.center.x, concernLable.center.y);
    concernLable.font = [UIFont systemFontOfSize:13];
    if (_model.concernCount.intValue < 10000) {
        concernLable.text = [NSString stringWithFormat:@"-- %@关注 --",_model.concernCount.stringValue];
    } else {
        concernLable.text = [NSString stringWithFormat:@"-- %.1f万关注 --",_model.concernCount.floatValue / 10000];
    }
    concernLable.textAlignment = NSTextAlignmentCenter;
    [_header addSubview:concernLable];
    concernLable.textColor = [UIColor colorWithWhite:0.902 alpha:1.000];
    
    //添加关注按钮
    self.concerBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _concerBtn.frame = CGRectMake(0, concernLable.frame.origin.y + concernLable.frame.size.height + 10, 80, 30);
    _concerBtn.center = CGPointMake(self.view.center.x, _concerBtn.center.y) ;
    _concerBtn.layer.cornerRadius = 15;
    //设置按钮背景颜色
    _concerBtn.backgroundColor = [UIColor redColor];
    [_concerBtn setTitle:@"＋ 关注" forState:UIControlStateNormal];
    [_concerBtn setTitle:@"√已关注" forState:UIControlStateSelected];
    [_concerBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [_concerBtn setTitleColor:[UIColor blackColor] forState:UIControlStateSelected];
    [self.concerBtn addTarget:self action:@selector(add:) forControlEvents:UIControlEventTouchUpInside];
    [_header addSubview:_concerBtn];
    
//    NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:@"Topic"];
//    NSError *error;
//    NSArray *arr = [self.manager.managedObjectContext executeFetchRequest:request error:&error];
//    //NSMutableArray *arrT = [NSMutableArray array];
//    for (Topic *m in arr) {
//        NSLog(@"%@", m.title);
//        if ([_model.title isEqualToString:m.title]) {
//            _concerBtn.selected = YES;
//        } else {
//            _concerBtn.selected = NO;
//        }
//    }
    
    NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:@"Topic"];
    NSError *error;
    NSArray *arr = [self.manager.managedObjectContext executeFetchRequest:request error:&error];
    NSMutableArray *arrT = [NSMutableArray array];
    for (Topic *m in arr) {
        [arrT addObject:m.title];
        NSLog(@"%@", m.title);
    }
    NSLog(@"%@", arrT);
    if ([arrT containsObject:_model.title]) {
        _concerBtn.selected = YES;
    } else {
        _concerBtn.selected = NO;
    }
    
    self.bigView = [[BaseView alloc] initWithFrame:CGRectMake(10, backImg.frame.origin.y + backImg.frame.size.height + 10, SCREEN_WIDTH - 20, 110)];
    [_header addSubview:self.bigView];
    self.bigView.layer.borderColor = [UIColor colorWithWhite:0.702 alpha:1.000].CGColor;
    self.bigView.layer.borderWidth = 1;
    
    //作者介绍
    UIImageView *expertImg = [[UIImageView alloc]initWithFrame:CGRectMake(10, 10, 40, 40)];
    [expertImg sd_setImageWithURL:[NSURL URLWithString:_model.headpicurl] placeholderImage:[UIImage imageNamed:@"User_Profiles_bg"]];
    expertImg.layer.cornerRadius = 20;
    expertImg.clipsToBounds = YES;
    [self.bigView addSubview:expertImg];
    
    //作者姓名
    self.nameLable = [[UILabel alloc]initWithFrame:CGRectMake(expertImg.frame.origin.x + expertImg.frame.size.width + 10, expertImg.frame.origin.y + 5, SCREEN_WIDTH / 5 * 4, 15)];
    _nameLable.text = [[_model.name stringByAppendingString: @"|"]stringByAppendingString:_model.title];
    _nameLable.numberOfLines = 0;
    _nameLable.font = [UIFont systemFontOfSize:13];
    _nameLable.textColor = [UIColor grayColor];
    [self.bigView addSubview:_nameLable];
    
    //作者描述
   // _descripLable.frame = CGRectMake(_nameLable.frame.origin.x, _nameLable.frame.origin.y + _nameLable.frame.size.height + 5, _header.frame.size.width / 5 * 4 - 30, 40);
    self.descripLable = [[UILabel alloc]initWithFrame:CGRectMake(_nameLable.frame.origin.x, _nameLable.frame.origin.y + _nameLable.frame.size.height + 5, (SCREEN_WIDTH - 20) / 5 * 4 - 30, 40)] ;
    _descripLable.numberOfLines = 2;
    _descripLable.textColor = [UIColor grayColor];
    _descripLable.text = _model.expertDescription;
    _descripLable.font = [UIFont systemFontOfSize:16];
    [self.bigView addSubview:_descripLable];
    
    //作者描述展开的按钮
    self.isSpread = NO;
    self.spreadBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _spreadBtn.frame = CGRectMake(0, 0, 30, 30);
    _spreadBtn.center = CGPointMake(self.view.center.x, _descripLable.frame.origin.y + _descripLable.frame.size.height + 15);
    [_spreadBtn setBackgroundImage:[UIImage imageNamed:@"iconfont-xiangxia"] forState:UIControlStateNormal];
    [_spreadBtn addTarget:self action:@selector(spreadAction) forControlEvents:UIControlEventTouchUpInside];
    [self.bigView addSubview:_spreadBtn];
    
    self.smallView = [[BaseView alloc] initWithFrame:CGRectMake(20, _bigView.frame.origin.y + _bigView.frame.size.height + 10, SCREEN_WIDTH - 30, 20)];
    [_header addSubview:_smallView];
    
    BaseLabel *questionLable = [[BaseLabel alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width , 20)];
    NSNumber *questionNum = [_expert objectForKey:@"questionCount"];
    NSNumber *answerNum = [_expert objectForKey:@"answerCount"];
    questionLable.text = [NSString stringWithFormat:@"%ld提问 · %ld回复", (long)questionNum.integerValue, (long)answerNum.integerValue];
    questionLable.textColor = [UIColor colorWithWhite:0.498 alpha:1.000];
    questionLable.textAlignment = NSTextAlignmentLeft;
    questionLable.font = [UIFont systemFontOfSize:14];
    [_smallView addSubview:questionLable];
    
    UISegmentedControl *seg = [[UISegmentedControl alloc] initWithItems:@[@"最新", @"最热"]];
    seg.frame = CGRectMake(_smallView.frame.size.width - 80, 0, 70, 20);
    seg.selectedSegmentIndex = 0;
    // 边框颜色和选中时的颜色
    seg.tintColor = [UIColor redColor];
    [_smallView addSubview:seg];
    [seg addTarget:self action:@selector(segClick:) forControlEvents:UIControlEventValueChanged];
    
    _header.frame = CGRectMake(0, 0, SCREEN_WIDTH, _smallView.frame.origin.y + _smallView.frame.size.height);
    [self.tableView setTableHeaderView:_header];
}

/* 更换数据:最新/最热 */
- (void)segClick:(UISegmentedControl *)seg
{
    if (seg.selectedSegmentIndex == 0) {
        self.dataArr = _latesArr;
    } else {
        self.dataArr = _hotArr;
    }
    [self dealData];
}

#pragma mark - 展开按钮方法
-(void)spreadAction
{
    if (!_isSpread) {
        //计算出来的高度
        CGFloat height = [HeightAdaption heightWithText:_model.expertDescription Size:16 Width:_header.frame.size.width / 5 * 4 - 20];
        //描述lable
        _descripLable.numberOfLines = 0;
        _descripLable.frame = CGRectMake(_nameLable.frame.origin.x, _nameLable.frame.origin.y + _nameLable.frame.size.height + 5,_header.frame.size.width / 5 * 4 - 20, height);
        _bigView.frame = CGRectMake(10, 200, SCREEN_WIDTH - 20, 70 + height);
        self.smallView.frame = CGRectMake(20, _bigView.frame.origin.y + _bigView.frame.size.height + 10, SCREEN_WIDTH - 30, 20);
        _header.frame = CGRectMake(0, 0, SCREEN_WIDTH, _smallView.frame.origin.y + _smallView.frame.size.height);
        //展开后按钮的位置和样式变化
        [_spreadBtn setBackgroundImage:[UIImage imageNamed:@"iconfont-xiangshang"] forState:UIControlStateNormal];
        _spreadBtn.center = CGPointMake(_descripLable.center.x, _descripLable.frame.origin.y + _descripLable.frame.size.height + 15);
        //展开后header大小变化
//        CGFloat h = height - 40;
//        _header.frame = CGRectMake(0, 0, self.view.frame.size.width, 350 + h);
        _tableView.tableHeaderView = _header;
        
        [_tableView reloadData];
    }else{
        //描述lable
        _descripLable.frame = CGRectMake(_nameLable.frame.origin.x, _nameLable.frame.origin.y + _nameLable.frame.size.height + 5, _header.frame.size.width / 5 * 4 - 30, 40);
        _descripLable.numberOfLines = 2;
        _bigView.frame = CGRectMake(10, 200, SCREEN_WIDTH - 20, 110);
        self.smallView.frame = CGRectMake(20, _bigView.frame.origin.y + _bigView.frame.size.height + 10, SCREEN_WIDTH - 30, 20);
        _header.frame = CGRectMake(0, 0, SCREEN_WIDTH, _smallView.frame.origin.y + _smallView.frame.size.height);
        //展开后按钮的位置和样式变化
        [_spreadBtn setBackgroundImage:[UIImage imageNamed:@"iconfont-xiangxia"] forState:UIControlStateNormal];
        _spreadBtn.center = CGPointMake(_descripLable.center.x, _descripLable.frame.origin.y + _descripLable.frame.size.height + 15);
        //收起后header
       // _header.frame = CGRectMake(0, 0, self.view.frame.size.width, 350);
        _tableView.tableHeaderView = _header;
        [_tableView reloadData];
    }
    _isSpread = !_isSpread;
}

#pragma mark - 创建tableView
- (void)createTableView
{
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 20, SCREEN_WIDTH, SCREEN_HEIGHT - 20) style:UITableViewStylePlain];
    _tableView.dataSource = self;
    _tableView.delegate = self;
    _tableView.separatorStyle = 0;
    [self.view addSubview:_tableView];
    [_tableView registerClass:[TopicDetailTableViewCell class] forCellReuseIdentifier:@"cell"];
    
    /* KVO */
    [self.tableView addObserver:self forKeyPath:@"contentOffset" options:NSKeyValueObservingOptionNew context:nil];
}

#pragma mark - KVO 观察后执行的方法
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context
{
    CGFloat newY = [[change objectForKey:@"new"] CGPointValue].y;
    if (newY > 190) {
        /* tabBar隐藏 */
        [UIView animateWithDuration:0.5 animations:^{
            _naviBar.alpha = 1;
        }];
    } else if (newY < 50) {
        /* tabBar出现 */
        [UIView animateWithDuration:0.5 animations:^{
            _naviBar.alpha = 0;
        }];
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _questionArr.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    TopicDetailModel *qModel = _questionArr[indexPath.row];
    CGFloat qH = [HeightAdaption heightWithText:qModel.content Size:17 Width:self.view.frame.size.width - 9 - self.view.frame.size.width / 8 - 40];
    TopicDetailModel *aModel = _answerArr[indexPath.row];
    CGFloat aH = [HeightAdaption heightWithText:aModel.content Size:17 Width:self.view.frame.size.width - 9 - self.view.frame.size.width / 8 - 40];
    return qH + aH + 160;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    TopicDetailTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (_questionArr.count != 0 && _answerArr.count != 0) {
        TopicDetailModel *qmodel = _questionArr[indexPath.row];
        TopicDetailModel *amodel = _answerArr[indexPath.row];
        cell.qcontent = qmodel.content;
        cell.acontent = amodel.content;
        [cell.askerImg sd_setImageWithURL:[NSURL URLWithString:qmodel.userHeadPicUrl] placeholderImage:[UIImage imageNamed:@"User_Profiles_bg"]];
        cell.askerLabel.text = qmodel.questionId;
        cell.questionLabel.text = qmodel.content;
        [cell.expertImg sd_setImageWithURL:[NSURL URLWithString:amodel.specialistHeadPicUrl] placeholderImage:[UIImage imageNamed:@"User_Profiles_bg"]];
        cell.expertLable.text = amodel.specialistName;
        cell.answerLable.text = amodel.content;
    }
    cell.selectionStyle = 0;
    return cell;
}

- (void)viewWillAppear:(BOOL)animated
{
    self.navigationController.navigationBarHidden = YES;
    
    
//    NSLog(@"%@", _model.title);
//    NSLog(@"%@", arrT);
//    if ([arrT containsObject:_model.title]) {
//        _concerBtn.selected = YES;
//    } else {
//        _concerBtn.selected = NO;
//    }
}

#pragma mark - 收藏按钮
- (void)add:(BaseButton *)button
{
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Topic" inManagedObjectContext:self.manager.managedObjectContext];
    NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:@"Topic"];
    NSError *error;
    NSArray *arr = [self.manager.managedObjectContext executeFetchRequest:request error:&error];
    button.selected = !button.selected;
    if (button.selected) {
        for (Topic *m in arr) {
            if ([m.title isEqualToString:_model.title]) {
                return;
            }
        }
        Topic *top = [[Topic alloc] initWithEntity:entity insertIntoManagedObjectContext:self.manager.managedObjectContext];
        top.expertId = _model.expertId;
        top.alias = _model.alias;
        top.picurl = _model.picurl;
        top.classification = _model.classification;
        top.name = _model.name;
        top.headpicurl = _model.headpicurl;
        top.title = _model.title;
        top.questionCount = _model.questionCount;
        top.answerCount = _model.answerCount;
        top.expertDescription = _model.expertDescription;
        //        for (Topic *m in arr) {
        //            if ([m.title isEqualToString:_model.title]) {
        //                return;
        //            }
        //        }
        //        Topic *top = [[Topic alloc] initWithEntity:entity insertIntoManagedObjectContext:self.manager.managedObjectContext];
        [self.manager saveContext];
    } else {
        for (Topic *m in arr) {
            if ([m.title isEqualToString:_model.title]) {
                [self.manager.managedObjectContext deleteObject:m];
            }
        }
        [self.manager saveContext];
    }
    //NSLog(@"数据库收藏:%@", arr);
    NSLog(@"url === %@", [self.manager applicationDocumentsDirectory]);
    [[NSNotificationCenter defaultCenter] postNotificationName:@"changeFollow" object:nil];
}

- (void)viewWillDisappear:(BOOL)animated
{
    self.navigationController.navigationBarHidden = NO;
    [_tableView removeObserver:self forKeyPath:@"contentOffset"];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
